<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\exchange\Order;
use app\admin\model\station\Station;
use app\common\controller\Backend;
use think\Session;
use think\Db;
use app\admin\model\Reportclock as ReportclockModel;
use app\admin\model\exchange\Ordergas;
use app\admin\model\exchange\Ordergoods;
use app\admin\model\exchange\Orderrecharge;
use app\admin\model\exchange\OrderGasInfo;
use app\admin\model\exchange\OrderGoodsInfo;
use Xpyun\model\PrintRequest;
use Xpyun\service\PrintService;
use Xpyun\util\NoteFormatter;
use app\admin\model\gas\Gasset;
use app\admin\model\gas\Gasgun;
use app\admin\model\gas\Gasoil;
use app\admin\model\goods_manage\Goods;
use app\admin\model\Printer;
use app\admin\model\system_config\Storeset;
use app\common\model\StoreConfig;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Reportclock extends Backend
{

    protected $agent_id = -1;
    protected $store_no = -1;
    protected $admin_id = -1;

    /**
     * Purchase模型对象
     * @var \app\admin\model\Purchase
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $user_info = Session::get('admin');//获取当前登录用户信息
        $this->agent_id = $user_info['agent_id'];
        $this->store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];

        $this->model = new \app\admin\model\Reportclock;
//        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function cashier_shift_new()
    {
        //获取当前用户信息
        $admin_info = Session::get('admin');
        if(!isset($admin_info['can_cash']) || (isset($admin_info['can_cash']) && $admin_info['can_cash']!=20) ){
            echo '无收银权限';
            die;//不存在收银状态或者收银状态不等于20
        }

        $admin_id = $admin_info['id'];
        $store_no = $admin_info['store_no'];
        $clock_in_datetime = '';
        $admin_mobile_info = '';
        $admin_mobile = $admin_info['mobile'];
        if($admin_mobile){
            $admin_mobile_info = '('.$admin_mobile.')';
        }
        $admin_info = $admin_info['nickname'].$admin_mobile_info;

        //获取油站信息
        $store_info_tmp = Station::where('store_no',$store_no)->select();
        $store_info = null;
        if(isset($store_info_tmp[0]) && $store_info_tmp[0]){
            $store_info = $store_info_tmp[0];
        }


        //查询最后一条记录和期间的订单信息
        $clock_in_time = null;
        $clock_status = null;
        $this_id = -1;
        $repo_info = ReportclockModel::where('admin_id',$admin_id)
            ->limit(1)
            ->order('id','desc')
            ->select();
        if(isset($repo_info[0]->clock_in)){
            $clock_in = $repo_info[0]->clock_in;
            $this_id = $repo_info[0]->id;
            $clock_in_datetime = $clock_in;
            $clock_in_time = time($clock_in);
        }
        if(isset($repo_info[0]->status)){
            $clock_status = $repo_info[0]->status;
        }

        //查询期间的订单数据
        $total_pay_price = 0;
        $price = [];
        if($clock_in_time && $clock_status == 10) {
            $clock_out_time = time();
            $all_order = Order::where('store_no', $store_no)
                ->where('createtime', '>', $clock_in_time)
                ->where('createtime', '<', $clock_out_time)
                ->select();

            foreach ($all_order as $item) {
                if ($item->status == 0) {
                    if (isset($price[$item->type])) {
                        $price[$item->type] = $price[$item->type] + $item->total_pay_price;
                    } else {
                        $price[$item->type] = $item->total_pay_price;
                    }
                    $total_pay_price = $total_pay_price + $item->total_pay_price;
                }

            }
        }

        $total_price = $total_pay_price;
        $recharge_price = isset($price[1]) ? $price[1] : 0;
        $gas_price = isset($price[2]) ? $price[2] : 0;
        $goods_price = isset($price[3]) ? $price[3] : 0;



        $this->view->assign("station_name", $store_info->name);
        $this->view->assign("admin_info", $admin_info);
        $this->view->assign("clock_in", $clock_in_datetime);
        $this->view->assign("total_price", $total_price);
        $this->view->assign("gas_price", $gas_price);
        $this->view->assign("goods_price", $goods_price);
        $this->view->assign("recharge_price", $recharge_price);
        $this->view->assign("this_id", $this_id);
        $this->view->assign("clock_status", $clock_status);
        return $this->view->fetch();

    }

    public function do_csn()
    {
        if (false === $this->request->isAjax()) {
            $this->error('xx');
            return false;
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        var_dump($params);
        //获取当前用户信息
        $admin_info = Session::get('admin');
        $admin_id = $admin_info['id'];
        $this_id = $params['this_id'];

        $repo_info = ReportclockModel::where('id',$this_id)
            ->where('admin_id',$admin_id)
            ->select();

        if(isset($repo_info[0]) && $repo_info[0]){
            if(isset($repo_info[0]->status) && $repo_info[0]->status == 20){
                $this->error('已经报班~');
                return  true;
            }
            $up_info = $this->format_params($params);
            $re = ReportclockModel::where('id',$this_id)->update($up_info);
            if($re){
                $this->error('更新成功~');
                return  true;
            }
            $this->error('更新失败！！！');
            return  false;

        }
        $this->error('查无此信息！！！');
        return  false;

    }

    private function format_params($params)
    {
        $re['clock_out'] = date('Y-m-d H:i:s');
        $re['total_price'] = $params['total_price'];
        $re['gas_price'] = $params['gas_price'];
        $re['goods_price'] = $params['goods_price'];
        $re['recharge_price'] = $params['recharge_price'];
//        $re['refund_price'] = $params['refund_price'];
        $re['status'] = 20;
        return $re;
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('store_no', $this->store_no)
            ->order($sort, $order)
            ->paginate($limit);
        $re_data_tmp = $list->items();
        $all_admin_tmp = Admin::where('store_no',$this->store_no)->select();
        $all_admin = [];
        foreach ($all_admin_tmp as $ad){
            $moblie_tmp = isset($ad->mobile) && $ad->mobile ? '('.$ad->mobile.')' : '';
            $all_admin[$ad->id] = $ad->nickname.$moblie_tmp;
            unset($moblie_tmp);
        }
        $re_data = [];
        foreach ($re_data_tmp as $item){
            $item->admin_name = isset($all_admin[$item->admin_id]) ? $all_admin[$item->admin_id] : '';
            $re_data[] = $item;
        }
//        var_dump($re_data_tmp);die;
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = NULL)
    {
        //获取油站信息
        $store_info_tmp = Station::where('store_no',$this->store_no)->select();
        $store_info = null;
        if(isset($store_info_tmp[0]) && $store_info_tmp[0]){
            $store_info = $store_info_tmp[0];
        }

        $row = $this->model->get($ids);

        //获取用户信息
        $all_admin_tmp = Admin::where('store_no',$this->store_no)->select();
        $all_admin = [];
        $all_admin_infos = [];
        foreach ($all_admin_tmp as $ad){
            $moblie_tmp = isset($ad->mobile) && $ad->mobile ? '('.$ad->mobile.')' : '';
            $all_admin[$ad->id] = $ad->nickname.$moblie_tmp;
            $all_admin_infos[$ad->id] = $ad;
            unset($moblie_tmp);
        }
//        var_dump($all_admin);die;
//        var_dump($row->admin_id);die;
        $admin_id = $row->admin_id;
        $admin_info = '';
        if(isset($all_admin[$admin_id]) && $all_admin[$admin_id]){
            $admin_info = $all_admin[$admin_id];
        }

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $this->view->assign("station_name", $store_info->name);
            $this->view->assign("admin_info", $admin_info);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

//            echo 444;die;
            if(isset($params['status']) && $params['status'] == 10 && isset($params['clock_in']) && $params['clock_in'] && isset($all_admin_infos[$params['admin_id']]->resttime) && $all_admin_infos[$params['admin_id']]->resttime){
//                echo 222;die;
                //获取上班时间戳和下班时间戳
                $order_clock_in_date = date('Y-m-d',strtotime($params['clock_in']));
                $order_clock_out_datetime = $order_clock_in_date.' '.$all_admin_infos[$params['admin_id']]->resttime;
                if(strtotime($order_clock_out_datetime) < strtotime($params['clock_in'])){
                    //下班是第二天
                    $order_clock_in_date = date('Y-m-d',strtotime($params['clock_in'])+86400);
                    $order_clock_out_datetime = $order_clock_in_date.' '.$all_admin_infos[$params['admin_id']]->resttime;

                }
                //查询是否存在下班前的报班数据
                $order_clock_out_datetime = $this->get_af_clockin_bf_clockout($params['clock_in'],$order_clock_out_datetime);
                $re_order_info = $this->order_info(strtotime($params['clock_in']),strtotime($order_clock_out_datetime));
                $params['total_price'] = $re_order_info['total_price'];
                $params['gas_price'] = $re_order_info['gas_price'];
                $params['goods_price'] = $re_order_info['goods_price'];
                $params['recharge_price'] = $re_order_info['recharge_price'];
                $params['clock_out'] = $order_clock_out_datetime;
                $params['status'] = 20;

            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    private function order_info($clock_in_time,$clock_out_time)
    {
        $total_pay_price = 0;
        //查询期间的订单数据
        $all_order = Order::where('store_no', $this->store_no)
            ->where('createtime', '>', $clock_in_time)
            ->where('createtime', '<', $clock_out_time)
            ->select();

        foreach ($all_order as $item) {
            if ($item->status == 0) {
                if (isset($price[$item->type])) {
                    $price[$item->type] = $price[$item->type] + $item->total_pay_price;
                } else {
                    $price[$item->type] = $item->total_pay_price;
                }
                $total_pay_price = $total_pay_price + $item->total_pay_price;
            }

        }

        $re['total_price'] = $total_pay_price;
        $re['recharge_price'] = isset($price[1]) ? $price[1] : 0;
        $re['gas_price'] = isset($price[2]) ? $price[2] : 0;
        $re['goods_price'] = isset($price[3]) ? $price[3] : 0;

        return $re;
    }

    private function get_af_clockin_bf_clockout($clock_in,$order_clock_out_datetime)
    {
        $re_tmp = ReportclockModel::where('clock_in','>',$clock_in)->where('clock_in','<',$order_clock_out_datetime)->select();
        if(isset($re_tmp[0]->clock_in) && $re_tmp[0]->clock_in){
            return $re_tmp[0]->clock_in;
        }

        return $order_clock_out_datetime;
    }
          /**
     * 对账
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function print($ids = null)
    {
        $row = $this->model->get($ids);
//        var_dump($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }


        $this->eightprint($row->clock_in,$row->clock_out,$row->store_no);
    	$this->success('打印成功');
    }
 public function eightprint($clock_in,$clock_out,$store_no)
    {
    	        /**
         * <BR>：换行符（同一行有闭合标签(如 </C>)则应放到闭合标签前面, 连续两个换行符<BR><BR>可以表示加一空行）
         *  <L></L>：左对齐
         *  <C></C>：居中对齐
         *  <R></R>：右对齐
         *  注意：同一行内容不能使用多种对齐方式，可通过补空格方式自定义对齐样式。
         *       58mm的机器，一行打印16个汉字，32个字母
         *       80mm的机器，一行打印24个汉字，48个字母
         *
         *  <N></N>：字体正常大小
         *  <HB></HB>：字体变高一倍
         *  <WB></WB>：字体变宽一倍
         *  <B></B>：字体放大一倍
         *  <CB></CB>：字体放大一倍居中
         *  <HB2></HB2>：字体变高二倍
         *  <WB2></WB2>：字体变宽二倍
         *  <B2></B2>：字体放大二倍
         *  <BOLD></BOLD>：字体加粗
         *  <IMG></IMG>：打印LOGO图片，需登录开放平台在【打印机管理=》设备管理】下通过设置LOGO功能进行上传。此处直接写入
         *             空标签, 如 <IMG></IMG> 即可, 具体可参考样例。
         *             图片宽度设置：可以通过 <IMG> 标签名称自定义，如 <IMG60> 表示宽度为60，相应的闭合标签 </IMG>
         *             不需要指定高度。<IMG> 标签不指定宽度默认为40，最小值为20，最大值为100
         *  <QR></QR>：二维码（标签内容是二维码值, 最大不能超过256个字符, 单个订单最多只能打印一个二维码）。
         *             二维码宽度设置：可以通过 <QR> 标签名称自定义，如 <QR180> 表示宽度为180，相应的闭合标签 </QR>
         *             不需要指定宽度。<QR> 标签不指定宽度默认为110，最小值为90，最大值为180
         *  <BARCODE></BARCODE>：条形码（标签内容是条形码值）
         */
//      $store_no = 1;
//      $osn = "2023020915430674623773";
        $clock_in_date = strtotime($clock_in);
        $clock_out_date = strtotime($clock_out);
        
        $all_oil = Ordergas::where('store_no',$store_no)
            ->where('is_pay',2)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('total_price');
        $real_oil = Ordergas::where('store_no',$store_no)
            ->where('is_pay',2)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('total_pay_price');
        
        $discount_price = Ordergas::where('store_no',$store_no)
            ->where('is_pay',2)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('discount_price');
        
        $tui_price = Ordergas::where('store_no',$store_no)
            ->where('is_pay',1)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('discount_price');
        
        $good_price = Ordergoods::where('store_no',$store_no)
            ->where('is_pay',2)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('total_pay_price');
            
            
        $rechange_price = Orderrecharge::where('store_no',$store_no)
            ->where('is_pay',2)
            ->where('createtime', '>', $clock_in_date)
            ->where('createtime', '<', $clock_out_date)
            ->sum('total_pay_price');
               
        $storeinfo = Storeset::where('store_no',$store_no)->find();
//      $order = Order::where('order_no', $osn)->find();
//      $ordergas = Ordergas::where('order_no', $osn)->find();
//      $ordergoods = Ordergoods::where('order_no', $osn)->find();
//      $ordergasinfo = OrderGasInfo::where('order_id', $ordergas['id'])->select();
//      $ordergoodsinfo = OrderGoodsInfo::where('order_id', $order_id)->select();
        $print = Printer::where('store_no', $store_no)->find();
        $printContent = "";

        $printContent = $printContent . "<C>" . "<B>".$storeinfo['store_name']."</B>" . "<BR></C>";
        $printContent = $printContent . "<C>" . "<N>开始时间:".$clock_in."</N>" . "<BR></C>";
        $printContent = $printContent . "<C>" . "<N>结束时间:".$clock_out."</N>" . "<BR></C>";
        $printContent = $printContent . "<BR>";
        $printContent = $printContent . "<L>"
        	. "对账汇总：<BR>"
            . "油品合计应收：" . '￥'.$all_oil . "<BR>"
            . "加油合计实收：" . '￥'.$real_oil . "<BR>"
            . "优惠合计金额：" . '￥'.$discount_price . "<BR>"
            . "退款合计金额：" . '￥'.$tui_price . "<BR>"
            . "商品合计实收：" . '￥'.$good_price . "<BR>"
            . "充值合计金额：" . '￥'.$rechange_price . "<BR>";
//      if($ordergoodsinfo)
//		{
//	        $printContent = $printContent . "商品" . str_repeat(" ",15) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
//	            . "<BR>";
//	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
//	        foreach ($ordergoodsinfo as $in => $it) {	
//	        	$goodinfo = Goods::where('id', $it['goods_id'])->find();
//	            $printContent = $printContent . NoteFormatter::formatPrintOrderItem($goodinfo['goods_name'], $it['num'], $it['unit_price']);
//	        }
//	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
//      }	
//      if($ordergasinfo)
//		{
//	        $printContent = $printContent . "油品" . str_repeat(" ",15) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
//	            . "<BR>";
//	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
//	        foreach ($ordergasinfo as $k => $v) {
//	        	$guninfo = Gasgun::where('id', $v['gas_gun_id'])->find();
//				$gasinfo = Gasset::where('id', $guninfo['gas_id'])->find();
//	            $printContent = $printContent . NoteFormatter::formatPrintOrderItem($gasinfo['gas_name'], $v['num'], $v['unit_price']);
//	        }
//	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
//      }
//      	
//      $printContent = $printContent . "<R>" . "合计：" . $total_pay_price . "元" . "<BR></R>";
//
        $printContent = $printContent . "<BR>";
//      $printContent = $printContent . "<L>"
////          . "客户地址：" . "珠海市香洲区xx路xx号" . "<BR>"
//          . "订单编号：" . $osn . "<BR>"
//          . "下单时间：" . date("Y-m-d H:i") . "<BR>";
////          . "备注：" . "少放辣 不吃香菜" . "<BR>";
//
        $printContent = $printContent . "<C>"
//          . "<QR>https://www.xpyun.net</QR>"
            . "</C>";


        $request = new PrintRequest();
        $request->generateSign();

        //*必填*：打印机编号
        $request->sn = $print['terminal_no'];

        //*必填*：打印内容,不能超过12K
        $request->content = $printContent;

        //打印份数，默认为1
        $request->copies = 1;

        //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
        $request->voice = 1;
        //打印模式：
        //值为 0 或不指定则会检查打印机是否在线，如果不在线 则不生成打印订单，直接返回设备不在线状态码；如果在线则生成打印订单，并返回打印订单号。
        //值为 1不检查打印机是否在线，直接生成打印订单，并返回打印订单号。如果打印机不在线，订单将缓存在打印队列中，打印机正常在线时会自动打印。
        $request->mode = 1;
        
        
        //支付方式：
        //取值范围41~55：
        //支付宝 41、微信 42、云支付 43、银联刷卡 44、银联支付 45、会员卡消费 46、会员卡充值 47、翼支付 48、成功收款 49、嘉联支付 50、壹钱包 51、京东支付 52、快钱支付 53、威支付 54、享钱支付 55
        //仅用于支持金额播报的芯烨云打印机。
        $paytype = 41;
//      if($pay_type == 1)$paytype = 42;
//      if($pay_type == 2)$paytype = 41;
//      if($pay_type == 3)$paytype = 44;

        $request->payType = '';

        //支付与否：
        //取值范围59~61：
        //退款 59 到账 60 消费 61。
        //仅用于支持金额播报的芯烨云打印机。
        $request->payMode = 60;

        //支付金额：
        //最多允许保留2位小数。
        //仅用于支持金额播报的芯烨云打印机。
        $request->money = '';
        
        
        $service = new PrintService();
        $result = $service->xpYunPrint($request);
//      if($pay_type == 5)$service->xpYunControlBox($request);
//      echo json_encode($request);
//        print $result->content->code . "\n";
//        print $result->content->msg . "\n";
//
//        //data:正确返回订单编号
//        print $result->content->data . "\n";
    }
}
